#!/bin/bash
# 服务器环境一键安装脚本
# 用于快速安装部署所需的所有环境

set -e

echo "=========================================="
echo "开始安装服务器环境..."
echo "=========================================="
echo ""

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then 
    echo "请使用root权限运行此脚本"
    exit 1
fi

# 1. 更新系统
echo "=== 1. 更新系统 ==="
apt-get update
apt-get upgrade -y
echo ""

# 2. 安装基础工具
echo "=== 2. 安装基础工具 ==="
apt-get install -y curl wget git vim
echo ""

# 3. 安装Python环境
echo "=== 3. 安装Python环境 ==="
apt-get install -y python3 python3-pip python3-venv
python3 --version
pip3 --version
echo ""

# 4. 安装MySQL
echo "=== 4. 安装MySQL ==="
apt-get install -y mysql-server
systemctl start mysql
systemctl enable mysql
echo "MySQL已安装，请运行以下命令配置："
echo "  sudo mysql_secure_installation"
echo ""

# 5. 安装Redis
echo "=== 5. 安装Redis ==="
apt-get install -y redis-server
systemctl start redis-server
systemctl enable redis-server
redis-cli ping
echo ""

# 6. 安装Nginx
echo "=== 6. 安装Nginx ==="
apt-get install -y nginx
systemctl start nginx
systemctl enable nginx
echo ""

# 7. 安装Node.js
echo "=== 7. 安装Node.js ==="
curl -fsSL https://deb.nodesource.com/setup_16.x | bash -
apt-get install -y nodejs
node --version
npm --version
echo ""

# 8. 安装防火墙
echo "=== 8. 配置防火墙 ==="
apt-get install -y ufw
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
echo "防火墙已配置（未启用），运行 'ufw enable' 启用"
echo ""

# 9. 创建必要的目录
echo "=== 9. 创建目录 ==="
mkdir -p /opt/nanchang_tour
mkdir -p /var/www/nanchang-tour
mkdir -p /var/log/nanchang-tour
mkdir -p /var/run/celery
chown -R www-data:www-data /var/log/nanchang-tour
chown -R www-data:www-data /var/run/celery
echo ""

echo "=========================================="
echo "环境安装完成！"
echo "=========================================="
echo ""
echo "下一步："
echo "1. 配置MySQL数据库"
echo "2. 上传项目代码到 /opt/nanchang_tour"
echo "3. 参考 docs/guides/快速部署步骤.md 继续部署"
echo ""

